This page last changed on Nov 29, 2004 by jcarreira.

这是包含在WW:WebWork示例war文件中一个使用XWork:校验框架的例子. 例子由三部分组成, 使用相同的活动类和视图页面(Velocity).

源代码

首先, 将validators.xml文件加入到源代码根路径下
<validators>
    <validator name="required" class="com.opensymphony.xwork.validator.validators.RequiredFieldValidator"/>
    <validator name="requiredstring" class="com.opensymphony.xwork.validator.validators.RequiredStringValidator"/>
    <validator name="int" class="com.opensymphony.xwork.validator.validators.IntRangeFieldValidator"/>
    <validator name="date" class="com.opensymphony.xwork.validator.validators.DateRangeFieldValidator"/>
    <validator name="expression" class="com.opensymphony.xwork.validator.validators.ExpressionValidator"/>
    <validator name="fieldexpression" class="com.opensymphony.xwork.validator.validators.FieldExpressionValidator"/>
    <validator name="email" class="com.opensymphony.xwork.validator.validators.EmailValidator"/>
    <validator name="url" class="com.opensymphony.xwork.validator.validators.URLValidator"/>
    <validator name="visitor" class="com.opensymphony.xwork.validator.validators.VisitorFieldValidator"/>
</validators>

本例中使用的活动类是ValidatedAction

package com.opensymphony.webwork.example;

import com.opensymphony.xwork.ActionSupport;

/**
 * ValidatedAction
 * @author Jason Carreira
 * Created Sep 12, 2003 9:23:38 PM
 */
public class ValidatedAction extends ActionSupport {
    private ValidatedBean bean = new ValidatedBean();
    private String name;
    private String validationAction = "basicValidation.action";

    public ValidatedBean getBean() {
        return bean;
    }

    public void setBean(ValidatedBean bean) {
        this.bean = bean;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getValidationAction() {
        return validationAction;
    }

    public void setValidationAction(String validationAction) {
        this.validationAction = validationAction;
    }
}

ValidatedAction的基本校验文件是ValidatedAction-validation.xml
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.dtd">
<validators>
    <field name="name">
        <field-validator type="requiredstring">
            <message>You must enter a name.</message>
        </field-validator>
    </field>
</validators>

它与其它校验文件放置在与类相同的目录下.

活动的表单是validationForm.vm

<html>
<head><title>Webwork Validation Example</title></head>
<body>
#if( $actionErrors.size() > 0 )
<p>
<font color="red">
<b>ERRORS:</b><br>
<ul>
#foreach( $error in $actionErrors )
<li>$error</li>
#end
</ul>
</font>
</p>
#end
<p>
<form name="myForm" action="${validationAction}" method="POST">
<input type="hidden" name="validationAction" value="${validationAction}"/>
Action Properties:
<br>
<table>
#tag( TextField "label=Name" "name=name" "value=name" )
</table>
Bean Properties:
#if( $stack.findValue("fieldErrors") )
    #set( $beanErrors = $stack.findValue("fieldErrors.get('bean')") )
    #if( $beanErrors.size() > 0 )
    <br>
    <font color="red">
    <b>Bean Errors:</b><br>
    <ul>
    #foreach( $beanError in $beanErrors )
    <li>$beanError</li>
    #end
    </ul>
    </font>
    #end
#end
<table>
#tag( TextField "label=Bean.Text" "name=bean.text" "value=bean.text" )<br>
#tag( TextField "label=Bean.Date" "name=bean.date" "value=bean.date" )<br>
#tag( TextField "label=Bean.Number" "name=bean.number" "value=bean.number" )<br>
#tag( TextField "label=Bean.Number2" "name=bean.number2" "value=bean.number2" )<br>
</table>
<input type="submit" value="Test Validation"/>
</form>
</body>

本例的成功页面非常简单, valid.vm
<html>
<head><title>WebWork Validation Test: Valid</title></head>
<body>
Input was valid!
</body>
</html>

后面我们将展示本例中其他配置文件的内容.

基本校验

基本校验例子定义在xwork.xml
<action name="basicValidation" class="com.opensymphony.webwork.example.ValidatedAction">
            <interceptor-ref name="validationWorkflowStack"/>

            <result name="success" type="dispatcher">valid.vm</result>
            <result name="input" type="dispatcher">validationForm.vm</result>
            <result name="error" type="dispatcher">validationForm.vm</result>
        </action>

这里interceptor-ref的值"validationWorkflowStack"定义在webwork-default.xml中, 它提供ValidationInterceptor(参见XWork:校验框架和DefaultWorkFlowInterceptor(参见XWork:DefaultWorkflow)的截取功能. 配置文件中所有的参数(本例中有一个)都从request取出设置到活动. 接下来, 执行校验, 最后将执行DefaultWorkflow(参见XWork:DefaultWorkflow).

本例十分简单, 仅使用了一个配置文件ValidatedAction-validation.xml. 这意味着只校验name字段是否输入内容.

访问者校验示例

注意: 查看另一个访问者字段校验器示例.

ValidatedAction包含一个普通Java对象引用, ValidatedBean:
package com.opensymphony.webwork.example;

import java.util.Date;

/**
 * ValidatedBean
 * @author Jason Carreira
 * Created Sep 12, 2003 9:24:18 PM
 */
public class ValidatedBean {
    private String text;
    private Date date = new Date(System.currentTimeMillis());
    private int number;
    private int number2;
    public static final int MAX_TOTAL = 12;

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public int getNumber2() {
        return number2;
    }

    public void setNumber2(int number2) {
        this.number2 = number2;
    }
}

ValidatedBean的校验配置文件是ValidatedBean-validation.xml

<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.dtd">
<validators>
    <field name="text">
        <field-validator type="requiredstring">
            <message key="invalid.text">Empty Text!</message>
        </field-validator>
    </field>
    <field name="date">
        <field-validator type="date">
            <param name="min">01/01/1970</param>
            <message key="invalid.date">Invalid Date!</message>
        </field-validator>
    </field>
    <field name="number">
        <field-validator type="int">
            <param name="min">1</param>
            <param name="max">10</param>
            <message key="invalid.number">Invalid Number!</message>
        </field-validator>
    </field>
</validators>

本例中, 增加一个VisitorFieldValidator来实现对ValidatedBean的校验. 活动定义在xwork.xml文件中:
<action name="visitorValidation" class="com.opensymphony.webwork.example.ValidatedAction">
            <interceptor-ref name="validationWorkflowStack"/>
            <param name="validationAction">visitorValidation.action</param>
            <result name="success">valid.vm</result>
            <result name="input">validationForm.vm</result>
            <result name="error">validationForm.vm</result>
        </action>

可以发现本利于基本校验的细微差别. 活动增加了一个静态参数. 该参数设置了对表单进行校验的活动(参见validationForm.vm).

活动的名字, visitorValidation映射到另一个文件ValidatedAction-visitorValidation-validation.xml中的校验活动
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.dtd">
<validators>
    <field name="bean">
        <field-validator type="required">
            <message>The bean must not be null.</message>
        </field-validator>
        <field-validator type="visitor">
            <message>bean: </message>
        </field-validator>
    </field>
</validators>

校验框架将基于类名(ValidatedAction), 活动别名(visitorValidation)和标准后缀(-validation.xml)组成文件名ValidatedAction-visitorValidation-validation.xml.

该文件为bean字段定义了两个校验器: required校验器保证bean不为null; VisitorFieldValidator. VisitorFieldValidator将使用ValidatedBean的校验配置并使用与ValidatedAction相同的校验上下文(validation context)visitorValidation. 因此将顺序查找文件ValidatedBean-validation.xml (ValidatedBean的缺省校验文件)和ValidatedBean-visitorValidation-validation.xml (本校验上下文使用的校验).

ValidatedBean-validation.xml如下:

<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.dtd">
<validators>
    <field name="text">
        <field-validator type="requiredstring">
            <message key="invalid.text">Empty Text!</message>
        </field-validator>
    </field>
    <field name="date">
        <field-validator type="date">
            <param name="min">01/01/1970</param>
            <message key="invalid.date">Invalid Date!</message>
        </field-validator>
    </field>
    <field name="number">
        <field-validator type="int">
            <param name="min">1</param>
            <param name="max">10</param>
            <message key="invalid.number">Invalid Number!</message>
        </field-validator>
    </field>
</validators>

该文件校验三个字段(text, date, and number)并未它们提供了消息. 消息键值将用于在ValidatedBean类指定的资源文件中查找文本. 与ValidatedBean在同一目录中文件名为ValidatedBean.properties

invalid.date=You must enter a date after ${min}.
invalid.text=You must enter some text.
invalid.number=You must enter a number between ${min} and ${max}.
invalid.total=The total of number and number2 must be less than ${@com.opensymphony.webwork.example.ValidatedBean@MAX_TOTAL}.

这些消息将用于任何与ValidatedBean有关的错误中. 如你所见, 消息体可以使用Bean, 截取器, 活动的属性(将按照这样的顺序进行搜索)进行参数化. 这也是一个使用静态字段的例子 ${@com.opensymphony.webwork.example.ValidatedBean@MAX_TOTAL}.

ValidatedBean-visitorValidation-validation.xml文件定义visitorValidation 校验上下文下的校验规则, 但它并不存在, 因此被忽略.

带有表达式校验器的访问者校验

最后一个例子的配置与上一个例子类似. 本例的xwork.xml配置和visitorValidation例子中的很相似
<action name="expressionValidation" class="com.opensymphony.webwork.example.ValidatedAction">
            <interceptor-ref name="validationWorkflowStack"/>
            <param name="validationAction">expressionValidation.action</param>
            <result name="success">valid.vm</result>
            <result name="input">validationForm.vm</result>
            <result name="error">validationForm.vm</result>
        </action>

文件ValidatedAction-expressionValidation-validation.xml定义该校验上下文的检验规则:

<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.dtd">
<validators>
    <field name="bean">
        <field-validator type="required">
            <message>The bean must not be null.</message>
        </field-validator>
        <field-validator type="visitor">
            <param name="context">expression</param>
            <message>bean: </message>
        </field-validator>
    </field>
</validators>

它几乎与ValidatedAction-visitorValidation-validation.xml文件一样, 但它为VisitorFieldValidator传递了一个context参数. 本例中, 不使用与ValidatedAction相同的校验上下文(expressionValidation), 它传递了另一个上下文(expression).

本例中, 针对ValidatedBean的校验文件已经存在, 名字是ValidatedBean-expression-validation.xml

<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.dtd">
<validators>
    <validator type="expression">
        <param name="expression">@com.opensymphony.webwork.example.ValidatedBean@MAX_TOTAL > (number + number2)</param>
        <message key="invalid.total">Invalid total!</message>
    </validator>
</validators>

这增加了一个对象级别的(与之相反的是字段级别)ExpressionValidator, 将number和number2字段的和与静态常量比较, 如果总和大于常量将增加一个错误信息.

VisitorFieldValidator错误信息注意事项

使用VisitorFieldValidator, 消息字段名使用对象的字段名. 本例中, ValidatedBean的字段"text", "date", "number"的错误信息将使用字段名"bean.text", "bean.date", "bean.number". 最后一个例子中的对象级别的ExpressionValidator产生的错误信息将作为一个字段级别的错误使用名字"bean"添加到活动中.
Document generated by Confluence on Dec 14, 2004 16:36